package org.springblade.modules.auth.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Map;

import static org.apache.logging.log4j.LogManager.getLogger;

/**
 * 类说明
 *
 * @author zhz
 * @since 2022/9/21
 */
public class SsoHttpUtils {

    private final static Logger log = getLogger(SsoHttpUtils.class);

    /*
     *  POST请求
     *  参数是：URL，jsonObject(请求参数封装成json对象)
     *
     * */
    public static String doPost(String url, JSONObject jsonObject) {
        //创建HttpClients对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建post请求对象
        HttpPost httpPost = new HttpPost(url);
        //创建封装请求参数对象，设置post请求参数
        StringEntity myEntity = new StringEntity(jsonObject.toJSONString(), ContentType.APPLICATION_JSON);
        myEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(myEntity);
        try {
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            //执行POST请求，获取请求结果
            HttpResponse response = httpClient.execute(httpPost);
            log.info("POST请求返回状态码{}",response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200) {
                // 发送成功
                return EntityUtils.toString(response.getEntity());
            } else {
                // 发送失败
                return null;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                if (httpClient != null) {
                    // 释放资源
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /*
     * GET请求，如果有请求参数，则拼接到到url后面
     * */
    public static String doGet(String url, Map<String,Object> param) {
        String symbolOne = "?";
        String symbol = "&";
        StringBuilder paramUrl = new StringBuilder();
        param.forEach((key,value) ->{
            if ("".equals(paramUrl.toString())){
                paramUrl.append(symbolOne);
            } else {
                paramUrl.append(symbol);
            }
            paramUrl.append(key).append("=").append(value);
        });
        url = url + paramUrl;
        //创建HttpClients对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建get请求对象
        HttpGet httpGet = new HttpGet(url);
        //设置请求配置参数
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setSocketTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setRedirectsEnabled(true)
                .build();
        httpGet.setConfig(config);
        try {
            //执行get请求
            HttpResponse response = httpClient.execute(httpGet);
            log.info("GET请求返回状态码{}",response.getStatusLine().getStatusCode());
            //获取返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                // 发送成功
                return EntityUtils.toString(response.getEntity());
            } else {
                // 发送失败
                return null;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                if (httpClient != null) {
                    // 释放资源
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

	public static JSONObject doGet(String url) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response  = httpclient.execute(httpGet);
		HttpEntity entity = response.getEntity();
		String entityContent = EntityUtils.toString(entity, "UTF-8");
		return (JSONObject) JSON.parse(entityContent);
	}

	public static JSONObject doPost(String url) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String entityContent = EntityUtils.toString(entity, "UTF-8");
		return (JSONObject) JSON.parse(entityContent);
	}
}
